import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/components" as Components
import "qrc:/qml/styles" as Styles

/**
 * @brief 系统日志面板
 * @details 用于 DashboardScreen，展示系统运行日志
 *          支持日志级别过滤、自动滚动、导出功能
 */
Rectangle {
    id: root
    color: Styles.Theme.surface
    border.color: Styles.Theme.border
    border.width: 1
    radius: Styles.Theme.radiusNormal

    // 外部绑定 ViewModel
    property var logViewModel: null

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingSmall

        // ==================== 标题栏 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            Text {
                text: qsTr("系统日志")
                color: Styles.Theme.textPrimary
                font.pixelSize: Styles.Theme.fontSizeNormal
                font.weight: Font.Bold
            }

            Item { Layout.fillWidth: true }

            // 日志计数徽章
            Rectangle {
                Layout.preferredWidth: Math.max(30, countText.implicitWidth + 12)
                Layout.preferredHeight: 20
                radius: 10
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1

                Text {
                    id: countText
                    anchors.centerIn: parent
                    text: logViewModel ? logViewModel.totalCount : 0
                    color: Styles.Theme.textPrimary
                    font.pixelSize: 10
                    font.weight: Font.Bold
                }
            }

            // 清空按钮
            Components.ActionButton {
                text: qsTr("清空")
                buttonType: "danger"
                implicitWidth: 48
                implicitHeight: 22
                onClicked: {
                    if (logViewModel) logViewModel.clearLogs()
                }
            }
        }

        // ==================== 日志级别筛选 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: 4

            Repeater {
                model: ListModel {
                    ListElement { level: "all"; text: qsTr("全部"); colorKey: "textSecondary" }
                    ListElement { level: "info"; text: qsTr("信息"); colorKey: "info" }
                    ListElement { level: "warn"; text: qsTr("警告"); colorKey: "warning" }
                    ListElement { level: "error"; text: qsTr("错误"); colorKey: "danger" }
                }

                delegate: Rectangle {
                    Layout.fillWidth: true
                    height: 24
                    radius: 4

                    property bool isSelected: logViewModel && logViewModel.levelFilter === model.level
                    property color buttonColor: getColorByKey(model.colorKey)

                    color: isSelected ? buttonColor : "transparent"
                    border.color: buttonColor
                    border.width: 1

                    RowLayout {
                        anchors.centerIn: parent
                        spacing: 3

                        Text {
                            text: model.text
                            color: isSelected ? Styles.Theme.textOnPrimary : buttonColor
                            font.pixelSize: 12
                            font.weight: Font.Bold
                        }

                        // 计数徽章
                        Rectangle {
                            visible: getCount(model.level) > 0
                            width: 16
                            height: 12
                            radius: 6
                            color: isSelected ? Qt.rgba(1, 1, 1, 0.3) : buttonColor

                            Text {
                                anchors.centerIn: parent
                                text: {
                                    var count = getCount(model.level)
                                    return count > 99 ? "99+" : count
                                }
                                color: Styles.Theme.textOnPrimary
                                font.pixelSize: 7
                                font.weight: Font.Bold
                            }
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            if (logViewModel) {
                                logViewModel.levelFilter = model.level
                            }
                        }
                    }

                    function getColorByKey(key) {
                        switch (key) {
                            case "info": return Styles.Theme.info
                            case "warning": return Styles.Theme.warning
                            case "danger": return Styles.Theme.danger
                            default: return Styles.Theme.textSecondary
                        }
                    }

                    function getCount(level) {
                        if (!logViewModel) return 0
                        switch (level) {
                            case "all": return logViewModel.totalCount
                            case "info": return logViewModel.infoCount
                            case "warn": return logViewModel.warnCount
                            case "error": return logViewModel.errorCount
                            default: return 0
                        }
                    }
                }
            }
        }

        // ==================== 日志列表 ====================
        ScrollView {
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true

            ListView {
                id: logListView
                model: logViewModel ? logViewModel.filteredModel : null
                spacing: 1

                // 自动滚动连接
                Connections {
                    target: logViewModel
                    function onScrollToBottom() {
                        if (logViewModel && logViewModel.autoScroll) {
                            Qt.callLater(function() {
                                logListView.positionViewAtEnd()
                            })
                        }
                    }
                }

                delegate: Rectangle {
                    width: logListView.width
                    height: Math.max(28, logContent.implicitHeight + 8)
                    color: index % 2 === 0 ? Styles.Theme.background : Styles.Theme.backgroundSecondary
                    radius: 2

                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: 6
                        anchors.rightMargin: 6
                        anchors.topMargin: 4
                        anchors.bottomMargin: 4
                        spacing: 6

                        // 时间戳
                        Text {
                            text: model.timeString || ""
                            color: Styles.Theme.textTertiary
                            font.pixelSize: 12
                            font.family: "Consolas"
                            Layout.preferredWidth: 60
                        }

                        // 级别标签
                        Rectangle {
                            Layout.preferredWidth: 32
                            Layout.preferredHeight: 12
                            radius: 6
                            color: getLogLevelColor(model.level)

                            Text {
                                anchors.centerIn: parent
                                text: getLevelText(model.level)
                                color: Styles.Theme.textOnPrimary
                                font.pixelSize: 9
                                font.weight: Font.Bold
                            }
                        }

                        // 来源（可选显示）
                        Text {
                            visible: model.source && model.source.length > 0
                            text: "[" + (model.source || "") + "]"
                            color: Styles.Theme.textSecondary
                            font.pixelSize: 11
                            font.family: "Consolas"
                            Layout.preferredWidth: visible ? 130 : 0
                            elide: Text.ElideRight
                        }

                        // 日志内容
                        Text {
                            id: logContent
                            text: model.message || ""
                            color: model.level === "error" ? Styles.Theme.danger : Styles.Theme.textPrimary
                            font.pixelSize: 13
                            font.family: "Consolas"
                            wrapMode: Text.Wrap
                            Layout.fillWidth: true
                            maximumLineCount: 2
                            elide: Text.ElideRight
                        }
                    }
                }

                // 空状态
                Label {
                    visible: logListView.count === 0
                    anchors.centerIn: parent
                    text: qsTr("暂无日志")
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeNormal
                }
            }
        }

        // ==================== 底部控制栏 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            CheckBox {
                id: autoScrollCheckBox
                checked: logViewModel ? logViewModel.autoScroll : true
                text: qsTr("自动滚动")
                font.pixelSize: 10

                indicator: Rectangle {
                    implicitWidth: 12
                    implicitHeight: 12
                    x: autoScrollCheckBox.leftPadding
                    y: parent.height / 2 - height / 2
                    radius: 2
                    color: autoScrollCheckBox.checked ? Styles.Theme.primary : "transparent"
                    border.color: autoScrollCheckBox.checked ? Styles.Theme.primary : Styles.Theme.border
                    border.width: 1

                    Text {
                        anchors.centerIn: parent
                        text: "✓"
                        color: Styles.Theme.textOnPrimary
                        font.pixelSize: 9
                        visible: autoScrollCheckBox.checked
                    }
                }

                contentItem: Text {
                    text: autoScrollCheckBox.text
                    color: Styles.Theme.textSecondary
                    font.pixelSize: 10
                    leftPadding: autoScrollCheckBox.indicator.width + 4
                    verticalAlignment: Text.AlignVCenter
                }

                onCheckedChanged: {
                    if (logViewModel) {
                        logViewModel.autoScroll = checked
                    }
                }
            }

            Item { Layout.fillWidth: true }

            // 导出按钮
            Components.ActionButton {
                text: qsTr("导出")
                buttonType: "secondary"
                implicitWidth: 48
                implicitHeight: 22
                enabled: logViewModel && logViewModel.totalCount > 0
                onClicked: {
                    if (logViewModel) {
                        logViewModel.exportToFile("")
                    }
                }

                ToolTip.visible: hovered
                ToolTip.text: qsTr("导出日志到文件")
            }
        }
    }

    // ==================== 辅助函数 ====================

    function getLogLevelColor(level) {
        switch (level) {
            case "error": return Styles.Theme.danger
            case "warn": return Styles.Theme.warning
            case "info": return Styles.Theme.info
            case "debug": return Styles.Theme.textSecondary
            default: return Styles.Theme.textSecondary
        }
    }

    function getLevelText(level) {
        switch (level) {
            case "error": return "错误"
            case "warn": return "警告"
            case "info": return "信息"
            case "debug": return "调试"
            default: return level || ""
        }
    }
}
